<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator=">">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <!-- 头部警告区域 -->
      <el-alert
        title="注意：只允许为第三级分类设置相关参数"
        type="warning"
        :closable="false"
        show-icon
      >
      </el-alert>
      <!-- 选择商品分类 -->
      <el-row class="cat_opt">
        <el-col>
          <span>请选择商品分类:</span>
          <el-cascader
            v-model="selectedKeys"
            :options="cateList"
            :props="cateProps"
            clearable
            change-on-select
            @change="handlerChange"
          ></el-cascader> </el-col
      ></el-row>
      <!-- tab标签页 -->
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button
            type="primary"
            size="mini"
            :disabled="isBtnDisabled"
            @click="addDialogVisible = true"
            >添加参数
          </el-button>
          <!-- 动态参数表格 -->
          <el-table :data="manyTableDate" stripe border>
            <el-table-column type="expand">
              <template #default="scope">
                <el-tag
                  v-for="(item, i) in scope.row.attr_vals"
                  :key="i"
                  closable
                  @close="handlerClose(i, scope.row)"
                  >{{ item }}</el-tag
                >
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index"> </el-table-column>
            <el-table-column prop="attr_name" label="参数名称">
            </el-table-column>
            <el-table-column label="操作">
              <template #default="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="showEditDialog(scope.row.attr_id)"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="showDeleteDialog(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态参数" name="only">
          <el-button
            type="primary"
            size="mini"
            :disabled="isBtnDisabled"
            @click="addDialogVisible = true"
            >添加属性
          </el-button>
          <!-- 静态参数表格 -->
          <el-table :data="onlyTableDate" stripe border>
            <!-- 索引列 -->
            <el-table-column type="expand">
              <template #default="scope">
                <el-tag
                  v-for="(item, i) in scope.row.attr_vals"
                  :key="i"
                  closable
                  @close="handlerClose(i, scope.row)"
                  >{{ item }}</el-tag
                >
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index"> </el-table-column>
            <el-table-column prop="attr_name" label="参数名称">
            </el-table-column>
            <el-table-column label="操作">
              <template #default="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="showEditDialog(scope.row.attr_id)"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="showDeleteDialog(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
      <!-- 添加参数，属性的对话框 -->
      <el-dialog
        :title="'添加' + titleText"
        :visible.sync="addDialogVisible"
        width="30%"
        @close="addDialogClosed"
      >
        <el-form ref="addFormRef" :model="addForm" :rules="addFormRules">
          <el-form-item :label="titleText" prop="attr_name">
            <el-input v-model="addForm.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addParams">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 编辑参数，属性的对话框 -->
      <el-dialog
        :title="'编辑' + titleText"
        :visible.sync="editDialogVisible"
        width="30%"
        @close="editDialogClosed"
      >
        <el-form ref="editFormRef" :model="editForm" :rules="editFormRules">
          <el-form-item :label="titleText" prop="attr_name">
            <el-input v-model="editForm.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editParams">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 删除参数，属性的对话框 -->
      <el-dialog
        :title="'删除' + titleText"
        :visible.sync="deleteDialogVisible"
        width="30%"
      >
        <span slot="footer" class="dialog-footer">
          <el-button @click="deleteDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="deleteParams">删除</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 选择商品分类的id数组
      selectedKeys: [],
      // 商品分类列表
      cateList: [],
      // 级联选择器的配置对象
      cateProps: {
        value: "cat_id",
        label: "cat_name",
        chlidren: "chlidren",
      },
      activeName: "many",
      // 动态参数
      manyTableDate: [],
      // 静态参数
      onlyTableDate: [],
      // 控制添加对话框的关闭与隐藏
      addDialogVisible: false,
      // 控制编辑对话框的打开与关闭
      editDialogVisible: false,
      // 控制删除商品参数对话框的关闭与打开
      deleteDialogVisible: false,
      //编辑参数的表单数据
      editForm: {},
      // 添加参数的表单数据
      addForm: {},
      // 删除参数的表单数据
      deleteForm: {},
      // 添加参数验证规则
      addFormRules: {
        attr_name: [
          {
            required: true,
            message: "请输入参数名称",
            trriger: "blur",
          },
        ],
      },
      // 编辑参数验证规则
      editFormRules: {
        attr_name: [
          {
            required: true,
            message: "请输入参数名称",
            trriger: "blur",
          },
        ],
      },
    };
  },
  created() {
    this.getCateList();
  },
  methods: {
    // 获取商品分类数据
    async getCateList() {
      const { data: res } = await this.$http.get("categories");
      if (res.meta.status !== 200)
        return this.$message.error("获取商品数据失败");
      this.cateList = res.data;
    },
    // 获取参数列表数据
    async getParamsDate() {
      if (this.selectedKeys.length !== 3) {
        this.selectedKeys = [];
        this.manyTableDate = [];
        this.onlyTableDate = [];
        return;
      }
      // console.log(this.cateId);
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes`,
        {
          params: { sel: this.activeName },
        }
      );
      if (res.meta.status !== 200) return this.$message.error("获取失败");
      res.data.forEach((item) => {
        // 进行三元表达式的判断 为空的话返回一个空数组
        item.attr_vals = item.attr_vals ? item.attr_vals.split(",") : [];
        //控制文本框的隐藏与显示
        item.inputVisible = false;
        item.inputValue = "";
      });
      // console.log(res.data);
      if (this.activeName === "many") {
        this.manyTableDate = res.data;
      }
      this.onlyTableDate = res.data;
    },
    // 级联选择器发生变化 会触发这个函数
    async handlerChange() {
      this.getParamsDate();
    },
    // tab标签页点击事件的处理函数
    async handleClick() {
      this.getParamsDate();
    },
    // 添加参数对话框关闭时会触发该函数
    addDialogClosed() {
      this.$refs.addFormRef.resetFields();
    },
    // 点击按钮 添加参数
    addParams() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) return;
        const { data: res } = await this.$http.post(
          `categories/${this.cateId}/attributes`,
          {
            attr_name: this.addForm.attr_name,
            attr_sel: this.activeName,
          }
        );
        if (res.meta.status !== 201) return this.$message.error("添加参数失败");
        this.addDialogVisible = false;
        this.getParamsDate();
      });
    },
    // 展示编辑参数的对话框
    async showEditDialog(attr_id) {
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes/${attr_id}`,
        { params: { attr_sel: this.activeName } }
      );
      if (res.meta.status !== 200) return this.$message.error("获取失败");
      this.editForm = res.data;
      this.editDialogVisible = true;
    },
    // 重置修改的表单
    editDialogClosed() {
      this.$refs.editFormRef.resetFields();
    },
    // 点击按钮编修改参数
    editParams() {
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) return;
        const { data: res } = await this.$http.put(
          `categories/${this.cateId}/attributes/${this.editForm.attr_id}`,
          {
            attr_name: this.editForm.attr_name,
            attr_sel: this.activeName,
          }
        );
        if (res.meta.status !== 200) return this.$message.error("编辑失败");
        this.$message.success("编辑成功");
        this.editDialogVisible = false;
        this.getParamsDate();
      });
    },
    // 展示删除参数对话框
    async showDeleteDialog(attr_id) {
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes/${attr_id}`,
        { params: { attr_sel: this.activeName } }
      );
      if (res.meta.status !== 200) return this.$message.error("获取失败");
      this.deleteForm = res.data;
      this.deleteDialogVisible = true;
    },
    // 点击按钮 删除商品参数
    async deleteParams() {
      const confirmResult = await this.$confirm(
        "此操作将永久删除该参数，是否继续",
        "提示",
        {
          confirmButtonText: "确定",
          confirmButtonClass: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      if (confirmResult !== "confirm") {
        return this.$message.info("已取消删除");
      }
      const { data: res } = await this.$http.delete(
        `categories/${this.cateId}/attributes/${this.deleteForm.attr_id}`
      );
      if (res.meta.status !== 200) return this.$message.error("删除失败");
      this.$message.success("删除成功");
      this.deleteDialogVisible = false;
      this.getParamsDate();
    },
    // 文本框失去焦点或者按下enter都会触发该函数
    async handleInputConfirm(row) {
      if (row.inputValue.trim().length === 0) {
        row.inputValue = "";
        row.inputVisible = false;
        return;
      }
      // 输入了内容
      row.attr_vals.push(row.inputValue.trim());
      // 保存参数
      this.saveAttrVals(row);
      row.inputValue = "";
      row.inputVisible = false;
      this.getParamsDate();
    },
    // 保存参数
    async saveAttrVals(row) {
      // 发起请求保存新标签
      const { data: res } = await this.$http.put(
        `categories/${this.cateId}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(","),
        }
      );
      // console.log(res);
      if (res.meta.status !== 200) return this.$message.error("添加失败");
      this.$message.success("添加成功");
    },
    // 点击显示文本框
    showInput(row) {
      row.inputVisible = true;
      // 自动获得焦点 $nextTick方法的作用当页面元素重新渲染后才会执行里面的代码
      this.$nextTick(() => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    // 点击叉号 删除标签
    handlerClose(i, row) {
      row.attr_vals.splice(i, 1);
      this.saveAttrVals(row);
    },
  },
  computed: {
    // 控制按钮的启用与关闭
    isBtnDisabled() {
      if (this.selectedKeys.length !== 3) return true;
      return false;
    },
    // 当前选择的三级分类的id
    cateId() {
      if (this.selectedKeys.length === 3) return this.selectedKeys[2];
      return null;
    },
    // 动态计算标题文本
    titleText() {
      if (this.activeName === "many") return "动态参数";
      return "静态参数";
    },
  },
};
</script>

<style lang="less" scoped>
.cat_opt {
  margin: 15px 0;
}
.el-cascader {
  margin-left: 15px;
}
.el-tag {
  margin: 10px;
}
.input-new-tag {
  width: 120px;
}
</style>
